#pragma once

#include <boost/asio.hpp>
#include <boost/enable_shared_from_this.hpp>

#include "Reply.h"
#include "Request.h"
#include "RequestParser.h"


/// Represents a single thread-safe connection from a client
class ConcurrentTcpConnection : public boost::enable_shared_from_this<ConcurrentTcpConnection>
{
public:
	/// Construct a connection with the given io_service.
	ConcurrentTcpConnection(boost::asio::io_service &ioService);

	/// Get the socket associated with the connection
	boost::asio::ip::tcp::socket &getSocket()
	{
		return _socket;
	}

	/// Starts the first asynchronous operation for the connection
	void Start();

	typedef boost::shared_ptr<ConcurrentTcpConnection> Pointer;

private:
	/// Handles completion of a read operation
	void HandleRead(const boost::system::error_code &e, size_t bytes_transferred);

	/// Handles completion of a write operation
	void HandleWrite(const boost::system::error_code &e);

	/// Buffer for incoming data
	boost::array<char, 8192> _buffer;

	/// The reply to be sent back to the client
	Reply _reply;

	/// The incoming request
	Request _request;

	/// The parser for the incoming request
	RequestParser _requestParser;

	/// Socket for the connection
	boost::asio::ip::tcp::socket _socket;

	/// Strand to ensure the connection's handlers are not called concurrently
	boost::asio::io_service::strand _strand;
};
